package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.result.UserLoginMsg;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.service.IFileuploadService;
import com.cskaoyan.user.utils.ContentTypeSuffixUtils;
import com.cskaoyan.user.utils.UrlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * Auth: 杨宇健
 * Time: 2023/1/11 14:34
 * Description:
 **/

@Service
public class FileuploadServiceImpl implements IFileuploadService {

    @Autowired
    UrlUtils urlUtils;

    @Autowired
    MemberMapper memberMapper;

    @Override
    public void storageCreate(MultipartFile file, UserLoginMsg user) {
        String type = file.getContentType();

        if (type == null) {
            throw new BizException(SysRetCodeConstants.REQUEST_CHECK_FAILURE.getCode(),
                    SysRetCodeConstants.REQUEST_CHECK_FAILURE.getMessage()
                    );
        }

        String suffix = ContentTypeSuffixUtils.getSuffix(type);

        //重命名文件
        String key = UUID.randomUUID().toString() + suffix;
        String path = "avatar/user" + user.getUid() + "/" + key;

        Member member = new Member();
        member.setId(user.getUid());
        member.setUsername(user.getUsername());
        member.setFile(path);
        String absolutePaht = urlUtils.getLocalPath(path);
        member.setUpdated(new Date());
        File localFile = new File(absolutePaht);
        //如果文件及啊不存在，创建文件夹
        File parentFile = new File(localFile.getParent());
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        try {
            file.transferTo(localFile);
            memberMapper.updateByPrimaryKeySelective(member);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
